import React, {Component, PropTypes} from 'react';

import Relay from "react-relay";

import FindServiceDicListMutation from "../mutation/FindServiceDicListMutation";
import createEnterpriseServiceDicMutation from '../mutation/CreateEnterpriseServiceDicMutation';
import deleteEnterpriseServiceDicMutation from '../mutation/DeleteEnterpriseServiceDicMutation';

import _key from '../../../util/ReactKey';
import Util from "../../../util/Util"
import classNames from 'classnames';
import {_Input,_Select,_message,_Tag,_Tooltip,_Button,_notification,_Icon} from 'ANT_DE';

const Input = _Input,
    Tag = _Tag, Tooltip = _Tooltip,
    _Option = _Select.Option,
    message = _message,
    Button = _Button,
    notification = _notification,
    Icon = _Icon;

import {Modal} from 'fly';

export default class A extends Component {
    constructor(props) {
        super(props);
        this.state = {
            inputVisible:false,   // 服务类型添加按钮与输入按钮切换
            inputVisible_1:false,  // 服务类型2 添加与删除按钮切换
            newTagName:"",        // 服务类型添加时value值

            is_modal_enterType:false, //企业类型选择窗口显示

            //三份数组，三份选中状态
            enType_oneActive:0,
            enType_twoActive:null,
            enType_ThreeActive:[],

            OneList:[],
            TwoList:[],
            ThreeList:[],

            //显示的勾选项
            CheckedList:[],
            //需要发送的数据
            SubData:"",

            //显示的企业类型
            showEnType:""
        };

        this.handleModaEnterTypeClick = this.handleModaEnterTypeClick.bind(this);
        this.conmirBtn = this.conmirBtn.bind(this);
        this.handleInputConfirm = this.handleInputConfirm.bind(this);
        this.oneTypeSelect = this.oneTypeSelect.bind(this);

        this.EnterType_ok = this.EnterType_ok.bind(this);
        this.EnterType_cancel = this.EnterType_cancel.bind(this);

        //整理级别数组
        this.upDataTwoList = this.upDataTwoList.bind(this);
        this.upDataThreeList = this.upDataThreeList.bind(this);

        this.handleEnTypeThreeActive = this.handleEnTypeThreeActive.bind(this);
        this.handleDeleteService = this.handleDeleteService.bind(this);

        this.num = 0;
    }

    //liu _ callback
    componentWillMount(){
        this.enid = sessionStorage.getItem('enterpriseId');
    }

    // 点击弹框sdrtasdr
    handleModaEnterTypeClick(is_modal_enterType){
        if(!this.props.disabled){
            this.setState({is_modal_enterType});
            Relay.Store.commitUpdate(
                new FindServiceDicListMutation({
                    enid:this.enid
                }),
                {
                    onFailure: () => {
                        message.error("请求失败");
                    },
                    onSuccess: (response) => {
                        let data = response.findAllServiceDicList.data.dicList,
                            topSave = this.props.topSave.mainService,
                            onType = this.props.topSave.enType,
                            data_Arr = topSave.length > 1 ? topSave.split(",") : [],
                            Arr = [],
                            TwoActive = 0;

                        if(onType === "") onType=0;

                        this.setState({
                            OneList:data
                        },()=>{
                            // 根据父组件的enType_oneActive 整理二级菜单
                            data && this.upDataTwoList(onType);
                        });

                        // 只有在上次保存了之后
                        if( topSave ){
                            let _data = data[onType].subList;

                            for(let key in data_Arr){
                                for(let _item in _data){
                                    _data[_item].subList.map((item,index)=>{
                                        if(item.dicId === data_Arr[key]){
                                            Arr.push(item);
                                            TwoActive = _item
                                        }
                                    })
                                }
                            }

                            this.setState({enType_twoActive:parseInt(TwoActive,10)});
                            //更新二级服务列表
                            this.upDataThreeList(TwoActive);
                        }
                        //更新状态
                        this.setState({CheckedList:Arr,enType_oneActive:onType,enType_ThreeActive:data_Arr});
                    }
                }
            );
        }
    }

    //负责根据一级列表更新二级列表
    upDataTwoList(index){
        let {OneList} = this.state,TwoList = [];

        TwoList = OneList[index].subList;

        this.setState({TwoList})
    }

    //负责根据二级列表更新三级列表
    upDataThreeList(_index){
        console.log(this.state.TwoList[_index]);

        let ThreeList = [],
            subList = this.state.TwoList[_index].subList;

        ThreeList = subList;

        this.setState({
            ThreeList
        })
    }


    /*
    * 选中
    * */
    
    //企业类型选中 更新key
    oneTypeSelect(enType_oneActive){
        this.upDataTwoList(enType_oneActive);
        //备份一份
        // const obj = {
        //     ThreeList:,
        //     enType_twoActive:,
        //     enType_ThreeActive:,
        //     CheckedList:
        // }
        // 选中清空三级列表
        this.state.ThreeList = [];
        // 更改二级和三级选中的.
        this.state.enType_twoActive = null;
        this.state.enType_ThreeActive = [];
        this.state.CheckedList = [];

        this.setState({enType_oneActive});
    }
    // 二级菜单 选中与更新key
    handleEnTypeTwoActive(enType_twoActive){
        // 传两个 一级 和二级 更新三级
        this.upDataThreeList(enType_twoActive);
        this.setState({enType_twoActive:enType_twoActive});

    }
    // 三级菜单主要服务选中函数
    handleEnTypeThreeActive(enType_ThreeActive){
        // 生成当前选中数组 去二级里边
        const data = this.state.ThreeList[enType_ThreeActive],
              CheckedList = this.state.CheckedList,
              ThreeList = this.state.enType_ThreeActive;

        //加入当前状态s
        let Arr = ThreeList,
            of_index = ThreeList.indexOf(data.dicId);


        if(of_index > -1){
            Arr.splice(of_index,1);

            CheckedList.splice(of_index,1);

            this.setState({enType_ThreeActive:Arr,CheckedList:CheckedList});

        }else{
            Arr.push(data.dicId);
            CheckedList.push(data);
            this.setState({enType_ThreeActive:Arr,CheckedList:CheckedList});
        }
        console.log(this.state.CheckedList);
    }

    //input与button 显示与隐藏 true || false
    handleInputShowClick(inputVisible,e){
        this.setState({inputVisible},()=>{this.input.focus()});
    }
    handleInputShowClick_1(inputVisible_1,e){
        this.setState({inputVisible_1},()=>{this.input_1.focus()});
    }

    //  input新建标签value改变
    handleNewTagChange(e){
        this.setState({newTagName:e.target.value})
    }

    //  input新建标签提交方法asdasdsad
    handleInputConfirm(parentId,level){
        // 验证name.length  是否重名  新增的length
        let value = this.state.newTagName,
            x_List = level === 2 ? this.state.TwoList:this.state.ThreeList,
            end = ()=>{
                level === 2 ?  this.setState({newTagName:"",inputVisible:false}) :
                    this.setState({newTagName:"",inputVisible_1:false})
            };

        if(value.length > 10) {
            message.warning("添加此服务名称不可超过10个字符");
            end();
            return;
        }else if(value.indexOf(" ") !== -1 ){
            message.warning("名称含有非法字符,请更换");
            end();
            return;
        }else if(value === ""){
            end();
            return;
        }
        for(let item of x_List){
            if(  value == item.name ){
                message.warning("当前服务名称不可与其他名称相同");
                end();
                return;
            }
        }

        let loading = message.loading("正在添加，请稍等",0);
        // // Relay.Store.createEnterpriseServiceDicMutation
        Relay.Store.commitUpdate(
            new createEnterpriseServiceDicMutation({
                enid:this.enid,
                name:value,
                parentId:parentId,
                level:level,
            }),
            {
                onFailure: (errcode) => {
                    notification.open({
                        message: '网络错误',
                        description: `网络出现错误，请您刷新页面重试，或报告网站管理员`,
                        placement:"bottomLeft",
                        icon: <Icon type="smile-circle" style={{ color: '#ff6565', fontSize:35,marginTop:10}} />,
                    });
                },
                onSuccess: (response) => {
                    loading();
                    const data = response.createEnterpriseServiceDic.data;
                    notification.open({
                        message: data.value,
                        description: data.errorCode === "0" ? `您已成功添加${level-1}级主要服务，名称为${value}，此服务会一直为您保存。`:
                            `添加${level-1}级服务失败，请仔细阅读添加服务规则，提醒并检查添加服务个数。`,
                        placement:"bottomLeft",
                        icon: <Icon type="smile-circle" style={{ color: `#${data.errorCode != 0 ?  "ff6565" : "108ee9"}`, fontSize:35,marginTop:10}} />,
                    });
                    if(data.errorCode === "0"){
                        data.enterpriseServiceDic.subList = [];
                        x_List.push(data.enterpriseServiceDic);

                        //此处需要更改两处状态，因为点击二级菜单时需要从二级下获取三级列表;
                        if(level === 2){
                            let OneList = this.state.OneList;
                            OneList[this.state.enType_oneActive].subList.push(data.enterpriseServiceDic);
                            this.setState({TwoList:x_List})
                        }else{

                            let TwoList = this.state.TwoList;
                            //更新二级
                            TwoList[this.state.enType_twoActive].subList.push(data.enterpriseServiceDic);
                            //更新三级
                            this.setState({ThreeList:x_List})
                        }

                        console.log(x_List);
                    }
                }
            }
        );

        end();
    }


    //删除
    handleDeleteService(index,level,e){
        e.stopPropagation();
        console.log("触发删除");
        // // Relay.Store.createEnterpriseServiceDicMutation
        let state = this.state,
            data = level === 2 ? state.TwoList : state.ThreeList,
            oneActive = this.state.enType_oneActive,
            twoActive = this.state.enType_twoActive,
            CheckedList = this.state.CheckedList;

        Relay.Store.commitUpdate(
            new deleteEnterpriseServiceDicMutation({
                enid:this.enid,
                dicId:data[index].dicId,
            }),

            {
                onFailure:(error)=>{
                    notification.open({
                        message: '网络错误',
                        description: `网络出现错误，请您刷新页面重试，或报告网站管理员`,
                        placement:"bottomLeft",
                        icon: <Icon type="smile-circle" style={{ color: '#ff6565', fontSize:35,marginTop:10}} />,
                    });
                },
                onSuccess:(response)=>{
                    const _data = response.deleteEnterpriseServiceDic.data,
                          removeActiveItem = this.state.ThreeList[index],
                          removeTwoDicId = data[index].dicId;
                    if(_data.errorCode == 0){
                        message.success(`已成功删除`);
                        data.splice(index,1);      //固定更新二级和三级list列表.
                        if(level === 2){
                            let OneList = this.state.OneList,
                                Checked = [];
                            OneList[oneActive].subList.splice(index,1); // 更新企业类型中一级服务中数据.
                            this.state.ThreeList = [];      //删除一级服务后清空三级服务

                            for(let key in CheckedList){
                                if(CheckedList[key].parentId !== removeTwoDicId){
                                   void Checked.push(CheckedList[key])
                                }
                            }
                            this.setState({TwoList:data,enType_twoActive:null,OneList:OneList,CheckedList:Checked});
                        }else{
                            let TwoList = this.state.TwoList,
                                checkedIndex = CheckedList.indexOf(removeActiveItem);
                            console.log(CheckedList);
                            //根据dicid去checked里面找，然后删除  // 注意，以下使用indeof判断，必须对象必须是引用类型，否则找不到;
                            checkedIndex >= 0 && CheckedList.splice(checkedIndex,1);
                            TwoList[twoActive].subList.splice(index,1);
                            this.setState({ThreeList:data,TwoList:TwoList,CheckedList:CheckedList});
                        }

                    }else{
                        message.error(`${_data.value}，出现错误，请刷新页面或重试`)
                    }
                }
            }
        )
    }
    //modal ok
    EnterType_ok(is_modal_enterType){
        this.setState({is_modal_enterType});
        console.log("ok");
    }
    //modal cancel
    EnterType_cancel(is_modal_enterType){
        this.setState({is_modal_enterType});
    }
    //确定
    conmirBtn(){
        let data = this.state.OneList[this.state.enType_oneActive],
            SubData = [];
        // push新数组
        for(let item of this.state.CheckedList){
            SubData.push(item.dicId);
        }
        this.setState({showEnType:data.name,SubData:SubData.join(",")},()=>{
            console.log(this.state.SubData);
            //把当前选中的checked 列表发送到父组件的 mainService中
            this.props.updaChecked(this.state.SubData,this.state.enType_oneActive);
        });

        this.EnterType_ok(false);  //取消
    }

    saveInputRef = input => this.input = input;
    saveInputRef_1 = input => this.input_1 = input;

    render() {
        const {Sty} = this.props;
        const {inputVisible,
            inputVisible_1,
            newTagName,
            enType_oneActive,
            enType_twoActive,
            enType_ThreeActive,
            is_modal_enterType,
            OneList,
            TwoList,
            ThreeList,
            CheckedList,
            showEnType
        } = this.state;

        return <div>

            <span className="re_font--MicYaHei" style={{position:"absolute",left:"64px",top:"190px",fontSize:14}} >企业类型</span>

            <p style={Sty.p_companytype}>{showEnType}</p>

            <span onClick={ ()=>this.handleModaEnterTypeClick(true)}
                  className="company_entyp--icon"  style={{width:29,height:32,position:"absolute",left:"440px",top:"183px",
                cursor:"pointer",fontSize:"30px",lineHeight:"15px"}} />

                <Modal
                    title="企业类型"
                    visible={is_modal_enterType}
                    onOk={() => this.EnterType_ok(false)}
                    width={1100}
                    onCancel={() => this.EnterType_cancel(false)}
                    style={{marginTop:8,width:820}}
                    className='enType_Modal close_style_modal'
                >
                    <div className="enter_type_modal">
                        <div className="enter_type_content">
                            <div
                                ref={'enterpriseList'}
                                className="enter_type_side _side">
                                <span className="_left enter_type_tit "> 企业类型 </span>
                                <i className="entype_side--col"></i>
                                <_Select
                                    getPopupContainer={()=>this.refs.enterpriseList}
                                    size="large" className="aasdadsasd" style={{ width: 120 }}
                                          onChange={this.oneTypeSelect}
                                          value = {OneList.length ===0 ? "" : OneList[enType_oneActive].name}
                                >
                                    {
                                        OneList.map((item,index)=>
                                            <_Option key={item.dicId} value={String(index)}> {item.name} </_Option>
                                        )
                                    }
                                </_Select>
                            </div>
                            <div className="main_conm_side _side">
                                <span className="_left enter_type_tit"> 主要服务 </span>
                                <div className="service_container _left">
                                    <div className={classNames({service_header:true })}>
                                        {/*.ant-tag*/}
                                        <ul className="service_list _left">
                                            {
                                                TwoList.map((item,index)=>
                                                    <li key={item.dicId} >
                                                        <div data-show="true" className={classNames({"ant-tag":true,active:enType_twoActive === index })}
                                                             onClick={()=>this.handleEnTypeTwoActive(index)}
                                                        >
                                                            <span className="ant-tag-text">{item.name}</span>

                                                            {item.enid != 0 && <i className="anticon anticon-cross" onClick={(e)=>this.handleDeleteService(index,2,e)}></i>}
                                                        </div>
                                                    </li>
                                                )
                                            }
                                            <li>
                                                {
                                                    inputVisible && (
                                                        <Input
                                                            ref={this.saveInputRef}
                                                            type="text" size="small"
                                                            style={{ width: 60,borderRadius:7 }}
                                                            value={newTagName}
                                                            onChange={(e)=>this.handleNewTagChange(e)}
                                                            onBlur={()=>this.handleInputConfirm(OneList[enType_oneActive].dicId,2)}
                                                            onPressEnter={()=>this.handleInputConfirm(OneList[enType_oneActive].dicId,2)}
                                                        />
                                                    )
                                                }
                                            {
                                                !inputVisible && <Button size="small" type="dashed" onClick={(e)=>this.handleInputShowClick(true)} > <Icon type="plus" style={{marginLeft:0}}/> 新增</Button>
                                            }
                                            </li>
                                        </ul>
                                    </div>
                                    <div className="service_content_list">

                                        <ul className="service_business_list">
                                            {
                                                ThreeList.map((item,index)=>
                                                    <li
                                                        key={item.dicId}
                                                        className={ classNames({active:(enType_ThreeActive.indexOf(item.dicId) > -1) ,isCustom:item.enid!=0 })}
                                                        onClick={()=>{this.handleEnTypeThreeActive(index)}}
                                                    >{item.name}
                                                        {
                                                            item.enid != 0 && <i className="icon_incre" onClick={(e)=>this.handleDeleteService(index,3,e)}>  </i>
                                                        }
                                                    </li>
                                                )
                                            }
                                            <li style={{border:"none"}} className={classNames({hide:enType_twoActive === null})}>
                                                {
                                                    inputVisible_1 && (
                                                        <Input
                                                            ref={this.saveInputRef_1}
                                                            type="text" size="small"
                                                            style={{ width: 60,borderRadius:7 }}
                                                            value={newTagName}
                                                            onChange={(e)=>this.handleNewTagChange(e)}
                                                            onBlur={()=>this.handleInputConfirm(TwoList[enType_twoActive].dicId,3)}
                                                            onPressEnter={()=>this.handleInputConfirm(TwoList[enType_twoActive].dicId,3)}
                                                        />
                                                    )
                                                }
                                                {
                                                    !inputVisible_1 && <Button size="small" type="dashed" onClick={(e)=>this.handleInputShowClick_1(true)} >
                                                        <Icon type="plus" style={{marginLeft:0}}/>
                                                        新增
                                                    </Button>
                                                }
                                            </li>
                                        </ul>
                                    </div>
                                    <p className="alarm" style={{marginTop:5}}>
                                    {

                                        CheckedList.length === 0 ? <span> 当前您没有选择任何服务。 </span>:
                                            <div>
                                             已选择：
                                                {
                                                    CheckedList.map((item,index)=>
                                                        <span key={index}> {item.name} </span>
                                                    )
                                                }
                                            </div>

                                    }
                                    </p>
                                </div>
                            </div>
                        </div>
                    </div>
                </Modal>

        </div>
    }
}